﻿using RazorEngine;
using RazorEngine.Templating;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EmailTemplate
{
    public class Render
    {
       public string RenderHtml()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + "EmailTemplate\\Template1.cshtml";
            var template = File.ReadAllText(path);
            var model = new Model.Persons() { Name="gongjie",Age=32};
            for (int i = 0; i < 100; i++)
            {
                model.ChildPersons.Add(new Model.Persons() { Name="aa",Age=i});
            }
            //string result = Razor.Parse(template, model);
            //var result = Engine.Razor.RunCompile(template, "templateKey2", null, model);
            var tem=Engine.Razor.CompileRunner<Model.Persons>(template);
            string result="";
            for (int i = 0; i < 10; i++)
            {
                result = tem.Run(model);
            }
           var cq= CsQuery.CQ.CreateDocument(result);
            var cssTable = cq[".table"];
            cssTable.Css("width", "100%").Css("max-width", "100%").Css("margin-bottom", "20px").Css("background-color", "transparent")
                .Css("border-spacing", "0").Css("border-collapse", "collapse").Css("border-collapse", "separate").Css("border-spacing", "2px")
                .Css("border-color", "grey");
            var tr = cq[".table tr"];
            foreach (var item in "display: table-row; vertical-align: inherit; border-color: inherit;".Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var css = item.Split(new char[] { ':'},StringSplitOptions.RemoveEmptyEntries);
                tr.Css(css[0],css[1]);
            }
            var td = cq[".table tr td"];
            foreach (var item in "padding: 8px; line-height: 1.42857143; vertical-align: top; border-top: 1px solid #ddd;".Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var css = item.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                td.Css(css[0], css[1]);
            } 
            return cq.Document.Render();
        }
    }
}
